#!/bin/bash
# 备份数据库
# crontab 30 3 * * * source $HOME/.bash_profile && sh /sumz/script/mysql_bak.sh >> /sumz/mysql_bak.log 2>&1
# 定义备份目录
bakurl="/sumz/data_bak/mysql_bak_file/"

# 定义需要备份的项目名
projects=("nacos_config_v2" "nacos_config")

# 计算项目数量
num_projects=${#projects[@]}

# 获取当前星期几
ntime=$(date -d "$(date +%Y-%m-%d)" +%w)

# 备份函数
backup_project() {
    project_name=$1
    mkdir -p "$bakurl/$project_name"
    /usr/local/bin/kubectl exec mysql-0 -n base -ti -- mysqldump -B "$project_name" -uroot -pSumz | gzip > "$bakurl/$project_name/${project_name}_$(date +%Y-%m-%d_%H_%M).sql.gz"
}

# 删除一个月以前的文件（除星期五以外）
delete_old_files() {
    project_name=$1
    # 计算一个月前的时间戳
    rtime=$(date -d "$(date +%Y-%m-%d -d '-30 day')" +%s)
    cd "$bakurl/$project_name"
    for filename in $(ls "$bakurl/$project_name")
    do
        fntime=$(date -d $(ls --full-time $filename | awk {'print $6'}) +%w)
        baktime=$(date -d $(ls --full-time $filename | awk {'print $6'}) +%s)
        if [ $rtime -gt $baktime ] && [ $fntime -ne 5 ]
        then
            rm -f "$bakurl/$project_name/$filename"
        fi
    done
}

# 备份和删除文件
for ((i=num_projects-1; i>=0; i--))
do
    backup_project "${projects[$i]}"
    delete_old_files "${projects[$i]}"
done
